﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using Region.Properties;
using Region.Utils;
namespace Region
{
    public partial class BrowserForm : Form
    {
        Engine m_engine;
        Boolean m_selected;
        
        DirItem m_root;
        DirItem m_current;
        DirItem m_select;
        public delegate Boolean DelegateIsSelect(DirItem item);
        public delegate void DelegateSelect(DirItem item);
        public Region.BrowserForm.DelegateIsSelect isSelectItem;
        public Region.BrowserForm.DelegateSelect SelectItem;
        ToolStripMenuItem m_SelectMenuItem;
        public class E1
        {
            public String A1;
            public String A2;
        }
        public BrowserForm(Engine engine,DirItem root,Boolean Selected)
        {            
            m_engine = engine;
            m_root = root;
            m_selected = Selected;
            InitializeComponent();
            Text += " " + engine.Version;            
            //m_root.Add(new DirReestrProcuror(m_engine,"Проверки прокурора",""));
            /*m_root.Add(new DirProcuror(m_engine));// Раздел прокуроские проверки
            m_root.Add(new DirItem("Определения"));            
            
            m_root.Add(new DirProtokol(m_engine));
            m_root.Add(new DirItem("Планирование"));
            m_root.Add(new DirItem("Предписание"));
            m_root.Add(new DirItem("Отчёты и анализ"));
            m_root.Add(new DirItem("Администрирование"));
            m_root.Add(new DirItem("Рабочий календарь"));*/
            showDir(m_root);  
            //ShowPage(5,10,true);           
        }
        

        private void click_PathElement(object sender, EventArgs e)
        {
            ToolStripButton B = (ToolStripButton)sender;
            showDir((DirItem)B.Tag);
        }


        ObjectFormUtil OFU;
        private void filter_ParamElement(object sender, EventArgs e)
        {
            if (OFU != null)
            {
                OFU.set();
                m_current.Filter();
                showDir(m_current);
            }
        }
        private void click_SelectPage(object sender, EventArgs e)
        {                    
          Int32 Page = 0;
          if (sender is ToolStripComboBox) Page = (Int32)(((ToolStripComboBox)sender).SelectedItem);
          if (sender is ToolStripButton) Page =(Int32)((ToolStripButton)sender).Tag;          
          DirItem.DirItemParam Params = m_current.getParams();              
          if ((Int32)Params.getPole("Page")==Page) return;//Выбрана таже страница
          if (OFU != null)
          { 
            Params.setPole("Page",Page);
            m_current.Filter();
            showDir(m_current);
          }
        }
        void ShowPage(Int32 Page,Int32 NumPage,bool Show)
        {
          if (Page>NumPage) Page = NumPage;
          if (Page<1) Page = 1;
          Page1.Visible = false;
          PageCB2.Visible = false;
          PageCB1.Visible = false;
          PageC.Visible = false;
          PageCN1.Visible = false;
          PageCN2.Visible = false;          
          PageE1.Visible = false;
          PageLabel0.Visible = false;
          PageLabel1.Visible = false;
          PageLabel2.Visible = false;
          PageList.Visible = false;/**/
          if (Show)
          {            
            PageLabel0.Visible = true;
            PageC.Visible = true;
            PageList.Visible = true;
            PageC.Text = Page.ToString(); PageC.Tag = Page;
            PageCB1.Visible = Page>1;
            PageCB1.Text = (Page-1).ToString(); PageCB1.Tag = Page-1;
            PageCB2.Visible = Page>2;
            PageCB2.Text = (Page-2).ToString(); PageCB2.Tag = Page-2;
            Page1.Visible = Page>3;
            Page1.Text = (1).ToString(); Page1.Tag = 1;
            PageLabel1.Visible = Page>4;
            PageCN1.Visible = Page+1<=NumPage;
            PageCN1.Text = (Page+1).ToString(); PageCN1.Tag = Page+1;
            PageCN2.Visible = Page+2<=NumPage;
            PageCN2.Text = (Page+2).ToString(); PageCN2.Tag = Page+2;
            PageE1.Visible = Page<=NumPage-3;
            PageE1.Text = (NumPage).ToString(); PageE1.Tag = NumPage;
            
            PageLabel2.Visible = Page<=NumPage-4;
            PageList.Items.Clear();
            for(int p=1;p<=NumPage;p++)
              PageList.Items.Add(p);
            PageList.SelectedItem = Page;
          }
        }
        bool showParamList(DirItem item)
        {
            DirItem.DirItemParam Params = item.getParams();
            OFU = new ObjectFormUtil(m_engine, Params);
            if (Params == null) return false;
            String[] ParamsList = Params.getParams();            
            //ParamEditors = new Dictionary<Int32, Control>();
            ParamPanel.Controls.Clear();
            FlowLayoutPanel P = new FlowLayoutPanel();
            P.AutoScroll = true;
            P.Dock = DockStyle.Fill;
            ParamPanel.Controls.Add(P);
            Button B = new Button();
            B.Text = "Фильтровать";            
            B.Width = P.Width - P.Margin.Left - P.Margin.Right;
            B.Click += filter_ParamElement;
            P.Controls.Add(B);
            ShowPage(1,1,false);
            for (Int32 i = 0; i < ParamsList.Length; i++)
            {
                String Editor = Params.getEditor(ParamsList[i]);                    
                if (Editor != null)
                {
                    String Caption  = Params.getCaption(ParamsList[i]);
                    if (Caption!=null)
                    {
                      var L = new Label();
                      L.Text = Caption;
                      //L.Width = P.Width - 3;
                      L.MaximumSize = new Size(P.Width - P.Margin.Left - P.Margin.Right, 0);
                      L.AutoSize = true;
                      P.Controls.Add(L);
                    }
                    if (Editor == "Date")
                    {
                        var E = new DateTimePicker();
                        E.ShowCheckBox=true;                        
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "TextBox")
                    {
                        var E = new TextBox();
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "NumericUpDown")
                    {
                        var E = new NumericUpDown();
                        E.Maximum = Int32.MaxValue;
                        E.Minimum = Int32.MinValue;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "ListBox")
                    {
                        var E = new ListBox();
                        E.Sorted = true;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "ComboBox")
                    {
                        var E = new ComboBox();
                        E.Sorted = true;
                        E.DropDownStyle = ComboBoxStyle.DropDownList;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "CheckBox")
                    {
                        var E = new CheckBox();
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "TreeComboBox")
                    {
                        var E = new TreeComboBox();
                        //E.DropDownStyle = ComboBoxStyle.DropDownList;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }                    
                    else if (Editor == "UserSelector")
                    {
                        var E = new UserSelector();
                        E.engine= m_engine;
                        //E.DropDownStyle = ComboBoxStyle.DropDownList;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "OtdelSelector")
                    {
                        var E = new OtdelSelector();
                        E.engine= m_engine;
                        //E.DropDownStyle = ComboBoxStyle.DropDownList;
                        OFU.AddEditor(E, ParamsList[i], Params.getExProccessor(ParamsList[i]));
                        E.Width = P.Width - 3;
                        P.Controls.Add(E);
                    }
                    else if (Editor == "SelectPage")
                    {                                            
                      ShowPage((Int32)Params.getPole("Page"),(Int32)Params.getPole("NumPage"),true);
                    }
                    else if (Editor == "FilterManager")
                    {
                      Button B1 = new Button();
                      B1.Width = P.Width - 3;
                      B1.Text = Params.getCaption(ParamsList[i]);
                      Object Ex = Params.getExProccessor(ParamsList[i]);
                      B1.Click += (a,b)=>
                      {
                        Forms.SelectFilter sf = new Forms.SelectFilter(Params,Ex);
                        sf.ShowDialog();
                        showParamList(item);
                      };
                      
                      P.Controls.Add(B1);
                    }
                    else if (Editor == ""){}
                    else
                      throw new Exception("Редактор параметров '"+Editor+"' не поддерживается");
                }
                
            }
            OFU.get();
            return true;
        }
        bool showPath(DirItem item)
        {
            toolStrip2.Items.Clear();          
            for (DirItem i = item; i != null; i = i.Parent)
            {
                ToolStripButton B = new ToolStripButton();
                B.DisplayStyle = ToolStripItemDisplayStyle.Text;
                B.Text = (String)i.getData(0, "Caption"); ;
                B.Tag = i;
                B.Click += click_PathElement;
                B.BackColor = Color.White;
                toolStrip2.Items.Insert(0, B);
            }
            toolStrip2.Items.Insert(0, new ToolStripLabel("Адрес:"));
            return true;
        }
        public delegate void InvokeShowDirDelegate(DirItem item);
        void refreshItem(DirItem item)
        {
          Object[] pr = new Object[1];
          pr[0]=item;
          if (Created) BeginInvoke(new InvokeShowDirDelegate(showDir),pr);
        }
       
        void showDir(DirItem item)
        {
          if (m_current!=null) m_current.OnRefresh-=refreshItem;
          item.OnRefresh+=refreshItem;
          
            showPath(item);
            showAction(item);
            ShowPage(1,1,false);
            m_current = item;
            
            listDir.BeginUpdate();
            listDir.Items.Clear();
            ImageList ILL =  new ImageList();
            ImageList ILS = new ImageList();
            ILL.ImageSize = new Size(32, 32);
            ILS.ImageSize = new Size(16, 16);            
            listDir.Columns.Clear();
            Int32 NumColumn = item.getCountColumn();
            for (Int32 i = 0; i < NumColumn; i++)
            {
                ColumnHeader H = new ColumnHeader();
                H.Text = (String)item.getColumn(i, "Caption");
                Object Width = item.getColumn(i, "Width");
                if (Width is Int32) { H.Width = (Int32)Width; }
                if (Width is ColumnHeaderAutoResizeStyle)
                    H.AutoResize((ColumnHeaderAutoResizeStyle)Width);
                listDir.Columns.Add(H);
            }
            var FullNumItem = m_current.getData(0,"FullNumItem");
            if (FullNumItem!=null) LabelNumItem.Text = "Всего записей: "+((Int32)FullNumItem).ToString(); else LabelNumItem.Text="";
            Int32 K = 0;
            Object Value;
            foreach (DirItem Child in m_current.Childs)
            {
                ListViewItem i = new ListViewItem();
                if (!Child.Visible) continue;
                i.Tag = Child;                
                Value = Child.getData(0, "Caption"); i.Text = (String)(Value == null ? "" : Value);
                Value = Child.getData(0, "ToolTip"); i.ToolTipText = (String)(Value == null ? "" : Value);
                Value = Child.getData(0, "BackColor"); if (Value != null) i.BackColor = (Color)(Value);
                Value = Child.getData(0, "ForeColor"); if (Value != null) i.ForeColor = (Color)(Value);

                Value = Child.getData(0, "IconLarge"); if (Value != null) ILL.Images.Add((Image)Value); else ILL.Images.Add(Properties.Resources.Doc);
                Value = Child.getData(0, "IconSmall"); if (Value != null) ILS.Images.Add((Image)Value); else ILS.Images.Add(Properties.Resources.Doc);
                i.ImageIndex = K++;                
                for (Int32 j = 1; j < NumColumn; j++)
                {
                    ListViewItem.ListViewSubItem sub = new ListViewItem.ListViewSubItem();
                    sub.Text =(String)Child.getData(j, "Caption");
                    Value = Child.getData(j, "Caption"); sub.Text = (String)(Value == null ? "" : Value);                    
                    Value = Child.getData(j, "BackColor"); if (Value != null) sub.BackColor = (Color)(Value);
                    Value = Child.getData(j, "ForeColor"); if (Value != null) sub.ForeColor = (Color)(Value);
                    i.SubItems.Add(sub);
                }
                
                //i.ToolTipText = Child.ToolTip();                
                listDir.Items.Add(i);
            }
            listDir.View = item.ViewDir();
            for (Int32 i = 0; i < NumColumn; i++)
            {                                
                Object Width = item.getColumn(i, "Width");                
                if (Width is ColumnHeaderAutoResizeStyle)
                    listDir.AutoResizeColumn(i, (ColumnHeaderAutoResizeStyle)Width);
            }            
            listDir.LargeImageList = ILL;
            listDir.SmallImageList = ILS;

            //ParamPanel.Controls.Clear();
            ParamPanel.Visible = item.IsParamPanel();
            showParamList(item);
            listDir.EndUpdate();            
            return ;
        }
        private System.Collections.Generic.List<System.Windows.Forms.ToolStripItem> ActionItems;
        bool showAction(DirItem item,DirItem selectSubItem = null)
        {
          
          if (ActionItems!=null)
          {
            foreach(var i in ActionItems)
              toolStrip1.Items.Remove(i);
          }
          ActionItems = new List<ToolStripItem>();
          List<IEnumerable<DirItem.DirActionItem>> A  = new List<IEnumerable<DirItem.DirActionItem>>(){item.getData(0,"Action") as IEnumerable<DirItem.DirActionItem>,selectSubItem==null?null:selectSubItem.getData(0,"Action") as IEnumerable<DirItem.DirActionItem>};
          if (m_selected)
          {
            ToolStripMenuItem i  = new ToolStripMenuItem("Выбрать");
            i.DisplayStyle = ToolStripItemDisplayStyle.Text;
            i.Enabled = (isSelectItem==null)?false:isSelectItem(selectSubItem);
            m_SelectMenuItem = i;
            //i.Tag = Action;
            i.Click+=(sender,e)=>{if (this.SelectItem!=null) SelectItem(m_select);Close();};
            toolStrip1.Items.Insert(0,i);
            ActionItems.Add(i);
          }
          else{
            foreach(var Actions in A)
              if (Actions!=null)
                foreach(var Action in Actions.Reverse())            
            {
               ToolStripMenuItem i  = new ToolStripMenuItem(Action.Caption,Action.Icon);
               i.DisplayStyle = ToolStripItemDisplayStyle.Image;
               i.Tag = Action;
               i.Click+=CMenuItemClick;             
               if (Action.SubItems!=null && Action.SubItems.Count>0)
                 AddCMenuItems(i.DropDownItems,Action.SubItems);
               toolStrip1.Items.Insert(0,i);
               
               ActionItems.Add(i);
            }
          }
          return true;
        }
        private void listDir_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (listDir.SelectedItems.Count == 1)
            {
                DirItem Item = (DirItem)listDir.SelectedItems[0].Tag;
                Item.Open();
                if (Item.IsDir()) showDir(Item);
            }
        }
        private void DirUp_Click(object sender, EventArgs e)
        {
            if (m_current.Parent!=null) showDir(m_current.Parent);
        }
        private void ZoomIn_Click(object sender, EventArgs e)
        {
            Font = new Font(Font.FontFamily, (float)Math.Min(Font.Size * 1.2, 17.1));
        }
        private void ZoomOut_Click(object sender, EventArgs e)
        {
            Font = new Font(Font.FontFamily, (float)Math.Max(Font.Size / 1.2, 6.875));
        }

        private void Form2_FontChanged(object sender, EventArgs e)
        {
            listDir.Font = this.Font;
            showPath(this.m_current);
        }

        private void выходToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void listDir_SelectedIndexChanged(object sender, EventArgs e)
        {          
          contextMenuStrip1.Items.Clear();
          if (listDir.SelectedItems.Count>0)
          {
            m_select = (DirItem)listDir.SelectedItems[0].Tag;
           // DirItem item = (DirItem)listDir.SelectedItems[0].Tag;
            IEnumerable<DirItem.DirActionItem> Actions = m_select.getData(0,"Action") as IEnumerable<DirItem.DirActionItem>;            
            if (Actions!=null) 
              AddCMenuItems(contextMenuStrip1.Items, Actions);            

          }
          else
            m_select = m_current;
          if (m_SelectMenuItem!=null)
          {
            m_SelectMenuItem.Enabled = (isSelectItem==null)?false:isSelectItem(m_select);
          }
        }

        private void ParamPanel_Paint(object sender, PaintEventArgs e)
        {

        }
        
        void ToolStrip1ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
          
        }
        
        /*void DirPrintClick(object sender, EventArgs e)
        {          
        }*/
        void CMenuItemClick(object sender, EventArgs e)
        {
          ToolStripMenuItem item  = (ToolStripMenuItem)sender;
          DirItem.DirActionItem Action = (DirItem.DirActionItem)item.Tag;
          Action.Action(m_select);
        }
        void AddCMenuItems(ToolStripItemCollection Collection,IEnumerable<DirItem.DirActionItem> Actions)
        {
           foreach(var Action in Actions)
           {
             
             ToolStripMenuItem item  = new ToolStripMenuItem(Action.Caption,Action.Icon);
             item.Tag = Action;
             item.Click+=CMenuItemClick;             
             if (Action.SubItems!=null && Action.SubItems.Count>0)
               AddCMenuItems(item.DropDownItems,Action.SubItems);
             Collection.Add(item);
           }         
        }
        void ContextMenuStrip1Opening(object sender, CancelEventArgs e)
        {
        }
        
        void BrowserFormFormClosing(object sender, FormClosingEventArgs e)
        {
          if (m_current!=null) m_current.OnRefresh-=refreshItem;
        }
        
        
        void ListDirMouseClick(object sender, MouseEventArgs e)
        {

        }
        
        void ListDirItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {  
        }
        
        void ListDirMouseDown(object sender, MouseEventArgs e)
        {
          if (e.Button == MouseButtons.Right)
            if (listDir.SelectedItems.Count==1)
          {
            m_select = (DirItem)listDir.SelectedItems[0].Tag;
            // DirItem item = (DirItem)listDir.SelectedItems[0].Tag;
            IEnumerable<DirItem.DirActionItem> Actions = m_select.getData(0,"Action") as IEnumerable<DirItem.DirActionItem>;
            contextMenuStrip1.Items.Clear();
            if (Actions!=null)
            {
              AddCMenuItems(contextMenuStrip1.Items, Actions);
            }
            else
              contextMenuStrip1.Items.Clear();
            contextMenuStrip1.Show((Control)sender,e.Location);
          }
        }
		void Timer1Tick(object sender, System.EventArgs e)
		{
						Dictionary<Int32,TaskManager.Task> tl = m_engine.taskManager.RunTask;
			if (tl.Count>0)
			{
        TaskProgressBar1.Visible = true;
				foreach(TaskManager.Task t in tl.Values)
				{
					Int32 max = t.TaskMax;
					Int32 val = t.TaskValue;
					if (val>max) 
						val = max;
					if (TaskProgressBar1.Maximum != max) TaskProgressBar1.Maximum = max;
					if (TaskProgressBar1.Value != val) TaskProgressBar1.Value = val;
          String NameTask = t.TaskTitle +"\n"+t.TaskName;
          if (TaskProgressBar1.ToolTipText != NameTask) TaskProgressBar1.ToolTipText = NameTask;
          //if (label2.Text != t.TaskTitle) label2.Text = t.TaskTitle;
					//if (label1.Text != t.TaskName) label1.Text = t.TaskName;
					if (t.Status == TaskManager.Task.EStatus.End)
						this.DialogResult = DialogResult.OK;
					break;
				}
			}
			else
			{
				TaskProgressBar1.Visible = false;
			}
    }
  }
}
